package com.yunkeji.api.lock;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.lock.executor.RedissonLockExecutor;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yunkeji.dao.domain.AppUser;
import com.yunkeji.dao.mapper.AppUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/** @author 老张 */
@Service
@RequiredArgsConstructor
public class LockTask {

    private final LockTemplate lockTemplate;
    private final AppUserMapper appUserMapper;
    private static final String ONLY_ID = "only_id";
    /**
     * 获取唯一ID
     *
     * @return
     */
    @Deprecated
    public Long getOnlyId() {
        final LockInfo lockInfo =
                lockTemplate.lock(ONLY_ID, 30000L, 5000L, RedissonLockExecutor.class);
        if (null == lockInfo) {
            throw new RuntimeException("ID生成失败,请稍后再试");
        }
        // 获取锁成功，处理业务
        try {
            while (true) {
                long platformId = RandomUtil.randomLong(10000L, 99999999999L);
                AppUser appUser =
                        appUserMapper.selectOne(
                                Wrappers.lambdaQuery(AppUser.class)
                                        .eq(AppUser::getPlatformId, platformId));
                if (appUser != null) {
                    continue;
                } else {
                    return platformId;
                }
            }
        } finally {
            // 释放锁
            lockTemplate.releaseLock(lockInfo);
        }
    }
}
